package com.learn.demo.netty.codec;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;

public class NettyServer4ProtoBufDemo {
    public static void main(String[] args) {
        //只处理连接请求
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        //处理客户端业务
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            //服务端启动对象
            ServerBootstrap bootstrap = new ServerBootstrap();
            //链式编程
            bootstrap.group(bossGroup, workerGroup);
            bootstrap.channel(NioServerSocketChannel.class);
            bootstrap.option(ChannelOption.SO_BACKLOG, 128);
            bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
            bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    ChannelPipeline pipeline = socketChannel.pipeline();
                    //指定解码对象
                    pipeline.addLast("decoder", new ProtobufDecoder(MyDataInfo.MyMessage.getDefaultInstance()));
                    //自定义handler
                    pipeline.addLast(new NettyServerHandlerDemo());
                }
            });//设置服务器通道类型
//设置线程队列连接个数
//设置保持活动连接状态
//设置处理器
            System.out.println("Netty Server Is Ready...");
            //绑定服务器端口，并启动服务器
            ChannelFuture channelFuture = bootstrap.bind(6666).sync();
            channelFuture.addListener((ChannelFutureListener) future -> {
                if(channelFuture.isSuccess()){
                    System.out.println("Netty Server bind 6666 port success");
                }else {
                    System.out.println("Netty Server bind 6666 port fail");
                }
            });
            //监听服务通道关闭
            channelFuture.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //关闭资源
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }

    }
}
